package com.lzw;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

public class PasswordRealm extends AuthorizingRealm {
    @Override
    public void setName(String name) {
        super.setName("PasswordRealm");
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //参数authenticationToken：表示登录时包装的UsernamePasswordToken
        //通过用户名到数据库中查用户信息，封装成一个AuthenticationInfo对象返回，方便认证器进行对比
        String username = (String) authenticationToken.getPrincipal();
        //通过用户名查询数据库，将该用户对应的数据查询回来：账号、密码
        //假设查询数据库返回数据是：lizhiwei  123456
        if(!"lizhiwei".equals(username)){
            return null;
        }
        //模拟数据库中保存加密之后的密文：123456 + 账号 + 3次散列次数
        String password = "a2d4603a4a245501b8d7cbecf7f69d31";
        //info对象表示realm登录对比信息：参数1：用户信息（真实登录系统的用户对象），参数2：用户登录密码，参数3：盐  ，参数4：当前realm的名字
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,password, ByteSource.Util.bytes(username),this.getName());


        return info;
    }
}
